using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(Manager数据管理器))]
// [CanEditMultipleObjects]
public class 数据管理器编辑器 : UnityEditor.Editor
{
    private Manager数据管理器 manager;

    private void OnEnable()
    {
        manager = target as Manager数据管理器;
        
    }

    private string 基础路径 = "Assets/游戏资源/数据配置/";
    private string 后缀 = ".xlsx";

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        
        if (GUILayout.Button("拉取所有数据"))
        {
            var f = AssetDatabase.FindAssets("t:BaseModel");

            List<BaseModel> bs = new List<BaseModel>();
            var fieldbs = typeof(Manager数据管理器).GetField("all数据s", BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (var VARIABLE in f)
            {
                string path = AssetDatabase.GUIDToAssetPath(VARIABLE);
                var b = AssetDatabase.LoadAssetAtPath<BaseModel>(path);
                bs.Add(b);
            }

            foreach (var VARIABLE in bs)
            {
                // var t = VARIABLE.GetType();
                拉取数据(VARIABLE);
            }
            
            fieldbs.SetValue(manager,bs);
        }
    }

    private void 拉取数据(BaseModel b)
    {
        Type t = b.GetType();
        
        var attri = t.GetCustomAttribute<DataAttribute>();
        if (attri != null && !string.IsNullOrEmpty(attri.FileName))
        {
            string x = $"{基础路径}{attri.FileName}{后缀}";
            var fieldData = t.GetField("Datas", BindingFlags.NonPublic | BindingFlags.Instance);
            // Debug.Log(fieldData);

            if (fieldData != null && fieldData.FieldType.GenericTypeArguments.Length > 0)
            {
                var childT = fieldData.FieldType.GenericTypeArguments[0];
                Type listType = typeof(List<>).MakeGenericType(childT);
                var obj = 添加数据(listType,x);
                fieldData.SetValue(b,obj);

                if (!string.IsNullOrEmpty(attri.FileName2))
                {
                    string x2 = $"{基础路径}{attri.FileName2}{后缀}";
                    var adddata = 添加数据(listType,x2);
                    
                    var me = t.GetMethod("AddData");
                    me.Invoke(b, new object[] {adddata});
                }
            }
        }

        b.editor检查数据();
        
        EditorUtility.SetDirty(b);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

    private object 添加数据(Type listt, string p)
    {
        var e = new ExcelHelp(p);
        var content = e.get内容详情();

        var value = JsonConvert.DeserializeObject(content.sJson, listt);
        Debug.Log(value);

        return value;
    }
}
